package com.lzh.gulimall.ware.listener;

import com.alibaba.fastjson.TypeReference;
import com.lzh.common.to.OrderTo;
import com.lzh.common.to.mq.StockDetailTo;
import com.lzh.common.to.mq.StockLockedTo;
import com.lzh.common.utils.R;
import com.lzh.gulimall.ware.dao.WareSkuDao;
import com.lzh.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.lzh.gulimall.ware.entity.WareOrderTaskEntity;
import com.lzh.gulimall.ware.feign.OrderFeignService;
import com.lzh.gulimall.ware.feign.ProductFeignService;
import com.lzh.gulimall.ware.service.WareOrderTaskDetailService;
import com.lzh.gulimall.ware.service.WareOrderTaskService;
import com.lzh.gulimall.ware.service.WareSkuService;
import com.lzh.gulimall.ware.vo.OrderVo;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
@Slf4j
@Service
@RabbitListener(queues = "stock.release.stock.queue")
public class StockReleaseListener {
    @Autowired
    private WareSkuService wareSkuService;

    /**
     * 1、库存自动解锁
     * 下订单成功，库存锁定，接下来的业务是啊比，导致订单回滚，之前多订的库存，需要自动解锁
     * 2、订单失败是因为锁库存失败引起的
     *
     * 只要解锁库存的消息失败，一定要告诉服务解锁失败
     * @param to
     * @param message
     */
    @RabbitHandler
    public void  handleStockLockedRelease(StockLockedTo to, Message message, Channel channel) throws IOException {
        try {
            System.out.println("收到解锁库存的消息...");
            wareSkuService.unlockStock(to);

            //只回复当前消息已经处理完的ack给服务端,broker将移除当前消息
            //批量签收消息fasle
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            //basicReject表示消息拒绝以后重新放到队列里面，让别人继续消费解锁
            //参数一: 当前消息的tag
            //参数二:requeue=true将消息发回服务器，重新入队
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }

    }

    @RabbitHandler
    public void handleOrderCloseRelease(OrderTo orderTo, Message message, Channel channel) throws IOException {

        log.info("******收到订单关闭，准备解锁库存的信息******");

        try {
            wareSkuService.unlockStock(orderTo);
            // 手动删除消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            // 解锁失败 将消息重新放回队列，让别人消费
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }

}
